var express = require('express');
var router = express.Router();
// 引入黑盒
var { uploadFile } = require('../util/upload');
//引入转发接口
const userApi = require('../api/users')
var path = require('path');//地址内置模块
var util = require('util');//工具模块
var fs = require('fs')//文件操作内置模块
var unlink = util.promisify(fs.unlink)//promise封装
/* GET home page. */
//上传图片
router.post('/upload', async function (req, res, next) {
  let { data } = await uploadFile(req);//只用传入req对象给这个方法
  let { _id, url } = data;
  let result = await userApi.reqSever({ _id, url })
  res.send(result)
});
//删除图片
router.patch('/:_id', async function (req, res, next) {
  let { _id } = req.params;
  let { url } = req.query;
  console.log(url)
  // path.resolve(__dirname)当前路径
  let publicUri = path.resolve(__dirname, '../public');//
  let absUrl = path.join(publicUri, url);//完整路径
  console.log(absUrl);
  await unlink(absUrl)//封装的fs.unlink方法；删除文件
  //向接口服务器发送请求
  let data = await userApi.removeImg({ _id, url });
  res.send(data)
});

module.exports = router;